package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import butterknife.BindView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.FileListParams;
import com.isunland.managesystem.entity.LocaleWorkQueryCountParams;
import com.isunland.managesystem.entity.Plotmappinginformation;
import com.isunland.managesystem.entity.PlotmappinginformationDetailOriginal;
import com.isunland.managesystem.entity.SimpleDetailParams;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SysDistrict;
import com.isunland.managesystem.entity.SysDistrictListOriginal;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/4/17 14:11
 */
public class PlotmappinginformationDetailFragment
    extends SimpleDetailFragment<Plotmappinginformation>
    implements View.OnClickListener, AMapLocationListener {
  private static final int REQUEST_SELECT_FILE = 1;
  private static final int REQUEST_UPLOAD = 2;
  private static final int REQUEST_SELECT_ADDRESS = 3;
  /** 绘制地块 */
  private static final int MENU_ITEM_DRAW_AREA = 4;
  private static final int REQUEST_DRAW_AREA = 5;
  private static final int REQUEST_FILE = 6;
  private static final int REQUEST_ORGANIZATION = 7;
  /** 承包者 */
  @BindView(R.id.sl_tplotName) SingleLineView slTplotName;
  /** 联系方式 */
  @BindView(R.id.sl_contactInformation) SingleLineView slContactInformation;
  /** 地址 */
  @BindView(R.id.sl_address) SingleLineView slAddress;
  /** 地块面积 */
  @BindView(R.id.sl_plotArea) SingleLineView slPlotArea;
  /** 地块描述 */
  @BindView(R.id.sl_wplotDepict) MultiLinesView slWplotDepict;
  /** 附件 */
  @BindView(R.id.sl_fileOriginalName) SingleLineView slFileOriginalName;
  /** 区域 */
  @BindView(R.id.sl_region) SingleLineView slRegion;
  /** 所属组织 */
  @BindView(R.id.slv_organization) SingleLineView slvOrganization;
  /** 查看地块 */
  @BindView(R.id.sl_checkArea) SingleLineView slCheckArea;
  @BindView(R.id.sl_regStaffName) SingleLineView slRegStaffName;
  @BindView(R.id.sl_regDate) SingleLineView slRegDate;
  @BindView(R.id.sl_dataStatus) SingleLineView slDataStatus;
  @BindView(R.id.sl_checkStaffName) SingleLineView slCheckStaffName;
  @BindView(R.id.sl_checkDate) SingleLineView slCheckDate;
  /** 作业任务信息 */
  @BindView(R.id.sl_areaWorkInfo) SingleLineView slAreaWorkInfo;
  private String mDocPath;
  private String mCooperativeRegionCode;
  private String mSelectOrgCode;
  /** 主表id */
  private String mId;
  /** 保存 */
  private boolean isSubmit;
  private String mDataStatus;
  private AMapLocationClient mlocationClient;
  private String mLat;
  private String mLon;

  @Override protected SimpleDetailParams initParams() {
    SimpleDetailParams params = new SimpleDetailParams();
    params.setLayoutId(R.layout.fragment_plot_mapping_information_detail);
    params.setTitleId(R.string.plot);
    params.setClassOriginal(PlotmappinginformationDetailOriginal.class);
    return params;
  }

  @Override public void initData() {
    super.initData();

    if (mItem != null) {
      mId = TextUtils.isEmpty(mItem.getId()) ? UUID.randomUUID().toString() : mItem.getId();
      mDataStatus =
          TextUtils.isEmpty(mItem.getDataStatus()) ? DataStatus.NEW : mItem.getDataStatus();
      mDocPath = mItem.getFileOriginalName();
      mCooperativeRegionCode = mItem.getRegionId();
      mSelectOrgCode = mItem.getMemberCode();
    } else {
      mId = UUID.randomUUID().toString();
      mDataStatus = DataStatus.NEW;
    }
    startLocation();
  }

  private void startLocation() {
    if (mlocationClient == null) {
      //初始化定位
      mlocationClient = new AMapLocationClient(mActivity);
      //初始化定位参数
      AMapLocationClientOption locationOption = new AMapLocationClientOption();
      //设置定位回调监听
      mlocationClient.setLocationListener(this);
      //设置为高精度定位模式
      locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
      //设置定位参数
      mlocationClient.setLocationOption(locationOption);
      // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
      // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
      // 在定位结束后，在合适的生命周期调用onDestroy()方法
      // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
      mlocationClient.startLocation();//启动定位
    }
  }

  @Override protected void initViewAdd() {
    //新建时不绘制,是因为网页端会不显示.
    slCheckArea.setVisibility(View.GONE);
    //隐藏登记信息
    slRegStaffName.setVisibility(View.GONE);
    slRegDate.setVisibility(View.GONE);
    slDataStatus.setVisibility(View.GONE);
    slCheckStaffName.setVisibility(View.GONE);
    slCheckDate.setVisibility(View.GONE);
    slAreaWorkInfo.setVisibility(View.GONE);//新增时没有作业任务

    //设置点击事件
    slAreaWorkInfo.setOnClickContentListener(this);
    slFileOriginalName.setOnClickContentListener(this);
    slRegion.setOnClickContentListener(this);
    slvOrganization.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new SysOrgBelongDialogFragment(), REQUEST_ORGANIZATION);
      }
    });
  }

  @Override protected void initViewEdit(Plotmappinginformation mItem) {

    //设置点击事件
    slCheckArea.setOnClickContentListener(this);
    slAreaWorkInfo.setOnClickContentListener(this);
    slFileOriginalName.setHint("");
    slFileOriginalName.setOnClickContentListener(this);
    slRegion.setOnClickContentListener(this);
    slvOrganization.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new SysOrgBelongDialogFragment(), REQUEST_ORGANIZATION);
      }
    });
  }

  @Override protected void initViewDetail(Plotmappinginformation mItem) {
    slCheckArea.setOnClickContentListener(this);
    //设置点击事件
    slAreaWorkInfo.setOnClickContentListener(this);
    slFileOriginalName.setHint("");
    slFileOriginalName.setOnClickContentListener(this);
    //禁用修改
    slAddress.setEnabled(false);

    slCheckDate.setEnabled(false);
    slCheckStaffName.setEnabled(false);
    slContactInformation.setEnabled(false);
    slDataStatus.setEnabled(false);
    //slFileOriginalName.setEnabled(false);
    slPlotArea.setEnabled(false);
    slRegDate.setEnabled(false);
    slRegion.setEnabled(false);
    slvOrganization.setEnabled(false);
    slRegStaffName.setEnabled(false);
    slTplotName.setEnabled(false);
    slWplotDepict.setEnabled(false);
  }

  @Override protected void volleyPostConfirm() {
    if (slTplotName.isEmptyContent()
        || slContactInformation.isEmptyContent()
        || slAddress.isEmptyContent()
        || slWplotDepict.isEmptyContent()
        || slRegion.isEmptyContent()
        || slvOrganization.isEmptyContent()) {
      ToastUtil.show(R.string.completeWrite);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_PLOT_MAPPING_INFORMATION);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("wplotDepict", slWplotDepict.getTextContent());
    params.put("tplotName", slTplotName.getTextContent());
    params.put("address", slAddress.getTextContent());
    params.put("contactInformation", slContactInformation.getTextContent());
    params.put("plotArea", slPlotArea.getTextContent());
    params.put("region", slRegion.getTextContent());
    params.put("regionId", mCooperativeRegionCode);
    params.put("memberCode", mSelectOrgCode);
    params.put("memberName", slvOrganization.getTextContent());
    params.put("fileOriginalName", mDocPath);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        Base original = new Gson().fromJson(json, Base.class);
        ToastUtil.show(original.getMessage());
        if (original.getResult() == Base.SUCCESS) {
          if (!isSubmit) {

            mActivity.setResult(Activity.RESULT_OK);
            mActivity.finish();
          } else {
            volleypostStatus(DataStatus.SUBMIT);
          }
        }
      }
    });
  }

  @Override protected void volleyPostDelete() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_PLOT_MAPPING_INFORMATION);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new SimpleDetailResponse());
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //super.onCreateOptionsMenu(menu, inflater);
    if (mType == BaseParams.TYPE_ADD || mType == BaseParams.TYPE_EDIT) {
      inflater.inflate(R.menu.menu_confirm_submit, menu);
    }
    if (mType == BaseParams.TYPE_DETAIL) {

      switch (mDataStatus) {
        case DataStatus.NEW:
          inflater.inflate(R.menu.menu_alter_submit_delete, menu);
          menu.findItem(R.id.menu_item_submit).setTitle(R.string.submit);
          break;
        case DataStatus.NEWBACK:
          inflater.inflate(R.menu.menu_alter_submit_delete, menu);
          menu.findItem(R.id.menu_item_submit).setTitle(R.string.submit);
          break;
        case DataStatus.SUBMIT:
          inflater.inflate(R.menu.menu_customerrelation_back, menu);
          break;
        case DataStatus.PUBLIS:
          inflater.inflate(R.menu.menu_customerrelation_back, menu);
          break;
      }
    }
    //添加时去掉绘制地块,因为网页端会有问题.条件是非添加状态,并且是可修改状态.
    if ((mType != BaseParams.TYPE_ADD) && (DataStatus.NEW.equals(mDataStatus)
        || DataStatus.NEWBACK.equals(mDataStatus))) {
      menu.add(0, MENU_ITEM_DRAW_AREA, 0, getString(R.string.drawArea)).setIcon(R.drawable.add);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_submit:
        isSubmit = true;
        volleyPostConfirm();
        return true;
      case R.id.menu_item_confirm:
        isSubmit = false;
        volleyPostConfirm();
        return true;
      case R.id.menu_item_back:
        //if (!MyStringUtil.equals(CurrentUser.newInstance(mActivity).getJobNumber(),
        //    mItem.getRegStaffId())) {
        //  ToastUtil.show(R.string.onlyCreaterEdit);
        //  return true;
        //}
        volleypostStatus(DataStatus.NEWBACK);
        return true;
      case MENU_ITEM_DRAW_AREA:
        String url =
            MyStringUtil.connect(ApiConst.getAbsoluteUrl(ApiConst.URL_DRAW_MAP), "?ownedLandId=",
                mId, "&personLat=", mLat, "&personLng=", mLon);
        BaseParams params = new BaseParams();
        params.setRemark(url);
        params.setTitle("作业地块维护");
        LocaleWorkQueryCountPathActivity.newInstance(this, LocaleWorkQueryCountPathActivity.class,
            params, REQUEST_DRAW_AREA);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleypostStatus(String status) {
    if (TextUtils.isEmpty(status)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_STATUS_PLOT_MAPPING_INFORMATION);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("dataStatus", status);
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new SimpleDetailResponse());
  }

  @Override public void onClick(View v) {
    if (!(v.getTag() instanceof Integer)) return;
    int id = (int) v.getTag();
    if (id == R.id.sl_areaWorkInfo) {
      //作业地块
      LocaleWorkQueryCountParams params = new LocaleWorkQueryCountParams();
      params.setFrom(LocaleWorkQueryCountListFragment.FROM_PLOTMAPPINGINFORMATION);
      params.setAreaId(mId);
      params.setForbiddenAdd(true);
      LocaleWorkQueryCountListActivity.newInstance(this, LocaleWorkQueryCountListActivity.class,
          params, 0);
    }
    //附件
    if (id == R.id.sl_fileOriginalName) {
      //相关附件子表
      FileListParams params = new FileListParams();
      params.setMainId(mId);
      BaseVolleyActivity.newInstance(this, FileListActivity.class, params, REQUEST_FILE);

      //if (mType == BaseParams.TYPE_DETAIL) {
      //
      //}
      //  //详情里下载
      //  download();
      //} else {
      //  //新增,修改上传
      //  upload();
      //}
    }
    if (id == R.id.sl_region) {
      selectRegion();
    }
    if (id == R.id.sl_checkArea) {
      String url =
          MyStringUtil.connect(ApiConst.getAbsoluteUrl(ApiConst.URL_DRAW_MAP), "?ownedLandId=", mId,
              "&view=T", "&personLat=", mLat, "&personLng=", mLon);
      BaseParams params = new BaseParams();
      params.setRemark(url);
      params.setTitle("作业地块维护");
      LocaleWorkQueryCountPathActivity.newInstance(this, LocaleWorkQueryCountPathActivity.class,
          params, 0);
    }
  }

  /**
   * 选择区域
   */
  private void selectRegion() {
    //DialogFragment dialog = AddressSelectDialogFragment.newInstance("100",
    //    CurrentUser.newInstance(mActivity).getMemberCode());
    //dialog.setTargetFragment(this, REQUEST_SELECT_ADDRESS);
    //dialog.show(mActivity.getSupportFragmentManager(), "");

    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    params.setItem(new SysDistrict("中国", "100"));
    params.setChildField("code");
    params.setParentField("pcode");
    params.setTitleField("districtName");
    params.setTitle("选择地址");
    params.setClassOriginal(SysDistrictListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_ADDRESS);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("pcode", "100").put("memberCode", mCurrentUser.getMemberCode()));
    BaseVolleyActivity.newInstance(this, AddressTreeListActivity.class, params,
        REQUEST_SELECT_ADDRESS);
  }

  @SuppressWarnings("unused") private void selectFile() {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        REQUEST_SELECT_FILE);
  }

  @SuppressWarnings("unused") private void download() {
    if (mItem == null || TextUtils.isEmpty(mItem.getFileOriginalName())) return;
    ExtraDownLoadDialogFragment dialog =
        ExtraDownLoadDialogFragment.newInstance("", mItem.getFileOriginalName());
    FragmentManager fm = mActivity.getSupportFragmentManager();
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_SELECT_FILE && data != null) {
      String path = FileUtil.getPath(getActivity(), data.getData());
      if (!TextUtils.isEmpty(path)) {

        FileUploadDialgFragment dialog =
            FileUploadDialgFragment.newInstance(path, mId, "plot_mapping_information");
        dialog.setTargetFragment(this, REQUEST_UPLOAD);
        dialog.show(mActivity.getSupportFragmentManager(), "");
      }
    }
    if (requestCode == REQUEST_UPLOAD) {
      mDocPath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      slFileOriginalName.setTextContent(FileUtil.getFileNameByFilePath(mDocPath));
    }
    if (requestCode == REQUEST_SELECT_ADDRESS) {
      //mCooperativeRegionCode = data.getStringExtra(AddressSelectDialogFragment.EXTRA_CODE);
      //slRegion.setTextContent(data.getStringExtra(AddressSelectDialogFragment.EXTRA_NAME));

      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      SysDistrict item = ((SysDistrict) params.getItem());
      slRegion.setTextContent(item.getDistrictName());
      mCooperativeRegionCode = item.getCode();
    }
    //绘制地块完成后,更新记录会有面积
    if (requestCode == REQUEST_DRAW_AREA) {
      volleyPostInit();
    }

    if (requestCode == REQUEST_ORGANIZATION && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slvOrganization.setTextContent(value.getName());
      mSelectOrgCode = value.getId();
    }
  }

  /**
   * 8初始化记录,地块面积.
   */
  protected void volleyPostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_DETAIL_PLOT_MAPPING_INFORMATION);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    mActivity.volleyPost(url, params.getParams(), new SimpleInitResponse());
  }

  @Override protected void bindData(Plotmappinginformation mItem) {
    slAreaWorkInfo.setHint("");
    slCheckArea.setHint("");
    //数据适配
    if (mItem == null) return;
    slAddress.setTextContent(mItem.getAddress());
    slCheckDate.setTextContent(mItem.getCheckDate());
    slCheckStaffName.setTextContent(mItem.getCheckStaffName());
    slContactInformation.setTextContent(mItem.getContactInformation());
    slDataStatus.setTextContent(DataStatus.getDataStatusName(mItem.getDataStatus()));
    slFileOriginalName.setTextContent(FileUtil.getFileNameByFilePath(mItem.getFileOriginalName()));
    slPlotArea.setTextContent(mItem.getPlotArea());
    slRegDate.setTextContent(mItem.getRegDate());
    slRegion.setTextContent(mItem.getRegion());
    slvOrganization.setTextContent(mItem.getMemberName());
    slRegStaffName.setTextContent(mItem.getRegStaffName());
    slTplotName.setTextContent(mItem.getTplotName());
    slWplotDepict.setTextContent(mItem.getWplotDepict());
  }

  @Override public void onLocationChanged(AMapLocation amapLocation) {
    if (amapLocation == null) return;
    if (amapLocation.getErrorCode() != 0) {
      String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
      LogUtil.e("AmapErr", errText);
      return;
    }
    //定位成功
    LogUtil.i("location=" + amapLocation.getLatitude() + "," + amapLocation.getLongitude());
    mLat = MyStringUtil.valueOf(amapLocation.getLatitude());
    mLon = MyStringUtil.valueOf(amapLocation.getLongitude());
  }

  @Override public void onDestroy() {
    super.onDestroy();
    //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
    if (null != mlocationClient) {
      mlocationClient.onDestroy();
    }
  }
}
